<?php

namespace YCommerce\GlobalBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class ProduitAdmin extends Admin
{
    // Fields to be shown on create/edit forms
    protected function configureFormFields(FormMapper $formMapper)
    {
        $produit = $this->getSubject();
        $fileFieldOptions = array('required' => false);
        if ($produit && ($webPath = $produit->getWebPath())) {
            // get the container so the full path to the image can be set
            $container = $this->getConfigurationPool()->getContainer();
            $fullPath = $container->get('request')->getBasePath().'/'.$webPath;
            
            $cacheManager = $container->get('liip_imagine.cache.manager');
            $srcPath = $cacheManager->getBrowserPath($webPath, 'product');

            // add a 'help' option containing the preview's img tag
            $fileFieldOptions['help'] = '<img src="'.$srcPath.'" />';
        }
        
        $formMapper
            ->add('name', 'text', array('label' => 'Nom'))
            ->add('prix', 'money', array('label' => 'Prix'))
            ->add('file', 'file', $fileFieldOptions)
                
            ->add('age_min', 'integer', array(
                'label' => 'Age minimum',
                'required' => false
            ))
            ->add('age_max', 'integer', array(
                'label' => 'Age maximal',
                'required' => false
            ))
            ->add('sex', 'choice', array(
                'label'        => 'Sexe',
                'expanded'     => true,
                'choices'      => array('m' => 'Masculin', 'f' => 'Féminin', 'u' => 'Les deux'),
                'widget_type'  => 'inline'
            ))    
            ->add('gamme')
            ->add('humeurs', 'sonata_type_model', array('expanded' => true, 'multiple' => true))
            ->add('interets', 'sonata_type_model', array('expanded' => true, 'multiple' => true))
        ;
    }

    // Fields to be shown on filter forms
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('name')
            ->add('prix')
        ;
    }

    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('id')
            ->add('name')
            ->add('prix')
        ;
    }
    
    
    public function prePersist($product) {
        $this->manageFileUpload($product);
    }

    public function preUpdate($product) {
        $this->manageFileUpload($product);
    }

    private function manageFileUpload($product) {
        if ($product->getFile()) {
            $product->setUpdated(new \DateTime("now"));
        }
    }
}